package com.xtx.air.bo.trade.impl;

import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.xtx.air.bo.trade.ITradeBO;
import com.xtx.air.common.XtxCollectionUtils;
import com.xtx.air.common.XtxTradeUtils;
import com.xtx.air.common.enums.TradeStatus;
import com.xtx.air.dao.flight.IFlightDAO;
import com.xtx.air.dao.flight.IFlightStorageDAO;
import com.xtx.air.dao.trade.ITradeDAO;
import com.xtx.air.dao.trade.ITradeDetailsDAO;
import com.xtx.air.dataobject.FlightStorageDO;
import com.xtx.air.dataobject.TradeDO;
import com.xtx.air.dataobject.TradeDetailsDO;
import com.xtx.util.CollectionUtil;

public class TradeBOImpl implements ITradeBO {

	private Log logger = LogFactory.getLog(this.getClass());

	private ITradeDAO tradeDAO;
	private ITradeDetailsDAO tradeDetailsDAO;
	private IFlightDAO flightDAO;
	private IFlightStorageDAO flightStorageDAO;

	public void setFlightDAO(IFlightDAO flightDAO) {
		this.flightDAO = flightDAO;
	}

	public void setFlightStorageDAO(IFlightStorageDAO flightStorageDAO) {
		this.flightStorageDAO = flightStorageDAO;
	}

	public void setTradeDAO(ITradeDAO tradeDAO) {
		this.tradeDAO = tradeDAO;
	}

	public void setTradeDetailsDAO(ITradeDetailsDAO tradeDetailsDAO) {
		this.tradeDetailsDAO = tradeDetailsDAO;
	}

	@Override
	public boolean addTrade(TradeDO tradeDO) {
		try {
			List<TradeDetailsDO> tradeDetails = tradeDO.getTradeDetails();
			if (!CollectionUtil.isEmpty(tradeDetails)) {
				Long daily_num = tradeDAO.getMaxDailyNum() + 1;
				tradeDO.setDaily_num(daily_num);
				String tradeNumPrefix = XtxTradeUtils.generateTradeNumPrefix();
				String dailySeqLength7 = StringUtils.leftPad(String.valueOf(daily_num), 7, '0');
				tradeDO.setT_num(tradeNumPrefix + dailySeqLength7);
				tradeDAO.addTrade(tradeDO);
				for (TradeDetailsDO detailsDO : tradeDetails) {
					detailsDO.setTrade_num(tradeDO.getT_num());
					FlightStorageDO storageDO = new FlightStorageDO();
					storageDO.setFid(tradeDO.getFly_id());
					storageDO.setBoarding_date(tradeDO.getBroading_date());
					storageDO.setClass_type(detailsDO.getClass_type());
					List<FlightStorageDO> flightStorages = flightStorageDAO.findStorage(storageDO);
					storageDO = XtxCollectionUtils.returnOnlyOne(flightStorages);
					storageDO.setCurrent_count(storageDO.getCurrent_count() - 1);
					flightStorageDAO.updateStorage(storageDO);
				}
				tradeDetailsDAO.addTradeDetails(tradeDetails);
				return true;
			}
			logger.error("交易明细列表为空，信息添加失败");
		} catch (Exception e) {
			logger.error("交易信息添加失败", e);
		}
		return false;
	}

	@Override
	public TradeDO getTrade(String trade_num) {
		try {
			TradeDO tradeDO = new TradeDO();
			tradeDO.setT_num(trade_num);
			tradeDO = XtxCollectionUtils.returnOnlyOne(tradeDAO.findTrade(tradeDO));
			if (tradeDO != null) {
				tradeDO.setTradeDetails(this.findTradeDetailsList(tradeDO.getT_num()));
			}
			return tradeDO;
		} catch (Exception e) {
			logger.error("交易信息加载失败", e);
			return null;
		}
	}

	@Override
	public List<TradeDO> findTrade(TradeDO tradeDO) {
		try {
			if (tradeDO == null) {
				tradeDO = new TradeDO();
			}
			return tradeDAO.findTrade(tradeDO);
		} catch (Exception e) {
			logger.error("交易信息查询失败", e);
			return null;
		}
	}

	@Override
	public List<TradeDO> findTradeWithDetails(TradeDO tradeDO) {
		try {
			if (tradeDO == null) {
				tradeDO = new TradeDO();
			}
			List<TradeDO> tradeList = tradeDAO.findTrade(tradeDO);
			for (Iterator<TradeDO> it = tradeList.iterator(); it.hasNext();) {
				tradeDO = it.next();
				tradeDO.setTradeDetails(this.findTradeDetailsList(tradeDO.getT_num()));
			}
			return tradeList;
		} catch (Exception e) {
			logger.error("交易信息及明细信息查询失败", e);
			return null;
		}
	}

	@Override
	public boolean updateTradeStatus(String trade_num, TradeStatus tradeStatus) {
		TradeDO trade = this.getTrade(trade_num);
		if (trade == null) {
			logger.error("交易信息查询失败，更新交易状态错误");
			return false;
		}
		boolean updateStatusResult = updateStatus(trade_num, tradeStatus);
		if (updateStatusResult) {
			if (TradeStatus.CANCELED.equals(tradeStatus)) {
				// 取消订单恢复库存
				List<TradeDetailsDO> tradeDetails = trade.getTradeDetails();
				for (TradeDetailsDO detailsDO : tradeDetails) {
					detailsDO.setTrade_num(trade.getT_num());
					FlightStorageDO storageDO = new FlightStorageDO();
					storageDO.setFid(trade.getFly_id());
					storageDO.setBoarding_date(trade.getBroading_date());
					storageDO.setClass_type(detailsDO.getClass_type());
					List<FlightStorageDO> flightStorages = flightStorageDAO.findStorage(storageDO);
					storageDO = XtxCollectionUtils.returnOnlyOne(flightStorages);
					storageDO.setCurrent_count(storageDO.getCurrent_count() + 1);
					flightStorageDAO.updateStorage(storageDO);
				}
				return true;
			}
		}
		return false;
	}

	/**
	 * 更新交易状态
	 * 
	 * @param trade_num
	 * @param tradeStatus
	 * @return
	 */
	private boolean updateStatus(String trade_num, TradeStatus tradeStatus) {
		TradeDO tradeDO = new TradeDO();
		tradeDO.setT_num(trade_num);
		tradeDO.setTrade_status(tradeStatus.name());
		tradeDO.setModified_time(Calendar.getInstance().getTime());
		return tradeDAO.updateTrade(tradeDO);
	}

	/**
	 * 获取交易明细列表
	 * 
	 * @param trade_num
	 * @return
	 */
	private List<TradeDetailsDO> findTradeDetailsList(String trade_num) {
		TradeDetailsDO tradeDetailsDO = new TradeDetailsDO();
		tradeDetailsDO.setTrade_num(trade_num);
		return tradeDetailsDAO.findTradeDetails(tradeDetailsDO);
	}
}